<template>
  <div class="app-container">
    <div class="filter-container">
      <span class="filter-title filter-item">上架状态</span>
      <k-select
        v-model="listQuery.boxStatus"
        class="filter-item user-status"
        :select-params="dict.type.BOX_UPDOWN_STATUS"
        @handleSelectEvent="handleFilter"
      />
      <span class="filter-title filter-item">配置时间</span>
      <k-date-picker
        v-model="timeValue"
        class="filter-item"
        @hqchang="handleFilter"
      />
      <k-input
        v-model.trim="listQuery.key"
        class="filter-item"
        is-search
        placeholder="请输入关键词"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>
    <!-- openAssignAccountDialog -->
    <k-button
      v-if="authorityHandle(43)"
      class="top-btn"
      value="添加箱子"
      @click.native="addBoxDialog"
    />
    <k-button
      v-if="authorityHandle(43)"
      class="top-btn"
      value="删除箱子"
      @click.native="deleteBox"
    />
    <!-- <k-button class="top-btn" value="智能阶段分区" @click.native="smartDivideZone" /> -->
    <!-- <k-button class="top-btn" value="一键打折" @click.native="quickDiscount" /> -->
    <k-button
      style="margin-left: 10px"
      class="top-btn"
      value="设置类别"
      @click.native="categoryShowHandler"
    />
    <!--表格相关 -->
    <el-table
      :data="boxList"
      fit
      border
      highlight-current-row
      style="width: 100%; border-radius: 8px"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column
        v-if="authorityHandle(43)"
        min-width="60px"
        type="selection"
        align="center"
      />
      <el-table-column width="60px" label="序号" type="index" align="center" />
      <el-table-column min-width="120px" label="箱子图标" align="center">
        <template slot-scope="scope">
          <KImage
            :imagevalue="scope.row.imgUrl"
            width-item="50px"
            height-item="50px"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="boxName"
        min-width="120px"
        label="箱子名称"
        show-overflow-tooltip
        align="center"
      />
      <el-table-column
        prop="price"
        min-width="100px"
        label="箱子价格(R)"
        sortable="custom"
        align="center"
      />
      <el-table-column
        prop="percentUser"
        min-width="90px"
        label="即时进价"
        align="center"
      />
      <el-table-column
        prop="percentFission"
        min-width="90px"
        label="历史进价"
        align="center"
      />
      <!-- <el-table-column prop="percentFission" min-width="90px" label="主播通道利润" align="center" /> -->
      <!-- <el-table-column
        prop="fistStagePrice"
        min-width="100px"
        label="第一阶段期望价值"
        align="center"
      /> -->
      <el-table-column min-width="120px" label="饰品展示缩略图" align="center">
        <template slot-scope="scope">
          <KImage
            :imagevalue="scope.row.goodsImgUrl"
            width-item="50px"
            height-item="50px"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="openNum"
        min-width="90px"
        label="个数限制"
        align="center"
      /> -->
      <el-table-column
        prop="assembleTime"
        min-width="150px"
        label="配置时间"
        align="center"
      />
      <el-table-column
        prop="boxStatus"
        min-width="80px"
        label="上架状态"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag
            size="medium"
            :type="scope.row.boxStatus == 1 ? '' : 'danger'"
            >{{ scope.row.boxStatus == 1 ? "上架" : "下架" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column min-width="300px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button
              v-if="authorityHandle(43)"
              class="table-btn"
              value="修改箱子"
              @click.native="addBoxUpdateDialog(scope.row)"
            />
            <!-- <k-button class="table-btn" value="晶粹配置" @click.native="bulletSettingDialog(scope.row)" /> -->
            <k-button
              class="table-btn"
              value="配置饰品"
              @click.native="configBabyLib(scope.row.id, 43)"
            />
            <!-- :disabled="scope.row.boxStatus === 1 ? true : false" -->
            <!-- <k-button class="table-btn" value="活动福利配置" @click.native="welfareSettingDialog(scope.row)" /> -->
            <!-- <k-button class="table-btn" value="箱子限制" @click.native="addItemDialog(scope.row)" /> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />
    <!-- 添加箱子 addBox 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="addBox-dialog"
      :title="textMap[dialogStatus]"
      :show-foot="false"
      :two-btn="true"
      :close-fun="handleCloseDialog"
      @click="saveBoxData"
    >
      <el-form :model="addBoxInfo" :rules="rules" label-width="auto" class="form-modify" ref="addBoxInfo">
        <el-form-item label="箱子名称：" prop="boxName">
          <el-input
            v-model="addBoxInfo.boxName"
            show-word-limit
            placeholder="请输入饰品名称"
          />
        </el-form-item>
        <el-form-item label="选择类别：">
          <el-select v-model="addBoxInfo.levelId" placeholder="请选择">
            <el-option
              v-for="item in selectCategoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="箱子图标：">
          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.imgUrl"
            upload-style="img"
            @successUpload="successUpload($event, 0)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>
        <!-- <el-form-item label="饰品展示缩略图：" prop="iconUrl">
          <k-upload-file
            ref="upload2"
            v-model="addBoxInfo.goodsImgUrl"
            upload-style="img"
            @successUpload="successUpload($event, 1)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item> -->
        <!-- <el-form-item label="开箱动画：">
          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.openAnimationUrl"
            upload-style="img"
            @successUpload="successUpload($event, 2)"
          />
          <span style="color: #b2b2b2">闯关玩法使用，格式为a.png，可不传</span>
        </el-form-item>

        <el-form-item label="动画结束状态静图：">
          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.stopUrl"
            upload-style="img"
            @successUpload="successUpload($event, 3)"
          />
          <span style="color: #b2b2b2"
            >闯关玩法使用，配合上方开箱动画使用，可不传</span
          >
        </el-form-item> -->
      </el-form>
    </k-dialog>

    <!-- addBox 修改弹窗 -->
    <k-dialog
      :show-hide.sync="addBoxUpdate.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="addBox-dialog"
      title="修改箱子"
      :show-foot="false"
      :two-btn="true"
      @click="saveBoxData"
    >
      <el-form :model="addBoxInfo" :rules="rules" ref="addBoxInfo" label-width="auto" class="form-modify">
        <el-form-item label="箱子名称：" prop="boxName">
          <el-input
            v-model="addBoxInfo.boxName"
            show-word-limit
            placeholder="请输入箱子名称"
          />
        </el-form-item>
        <el-form-item label="选择类别：">
          <el-select v-model="addBoxInfo.levelId" placeholder="请选择">
            <el-option
              v-for="item in selectCategoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="箱子图标：">
          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.imgUrl"
            upload-style="img"
            @successUpload="successUpload($event, 0)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>
        <el-form-item label="饰品展示缩略图：">
          <k-upload-file
            ref="upload2"
            v-model="addBoxInfo.goodsImgUrl"
            upload-style="img"
            @successUpload="successUpload($event, 1)"
          />
          <span style="color: #b2b2b2">只能上传jpg/png文件，且不超过2M</span>
        </el-form-item>
        <!-- <el-form-item label="开箱动画：">
          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.openAnimationUrl"
            upload-style="img"
            @successUpload="successUpload($event, 2)"
          />
          <span style="color: #b2b2b2">闯关玩法使用，格式为a.png，可不传</span>
        </el-form-item>

        <el-form-item label="动画结束状态静图：">
          <k-upload-file
            ref="upload1"
            v-model="addBoxInfo.stopUrl"
            upload-style="img"
            @successUpload="successUpload($event, 3)"
          />
          <span style="color: #b2b2b2"
            >闯关玩法使用，配合上方开箱动画使用，可不传</span
          >
        </el-form-item> -->
      </el-form>
    </k-dialog>
    <!-- 智能阶段分区 弹窗 -->
    <k-dialog
      :show-hide.sync="smartDivideZoneDialog"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="智能阶段分区"
      :show-foot="false"
      :two-btn="authorityHandle(43)"
      @click="saveSmartDivideZone"
    >
      <div class="dialog-warningSetting">
        <ul>
          <li
            v-for="(divideZoneItem, index) in divideZone.divideZoneArray"
            :key="divideZoneItem.id"
          >
            <span class="warning-title">阶段{{ index + 1 }}： 溢出箱价 </span>
            <el-input
              v-model.number="divideZoneItem.minPercent"
              :readonly="!authorityHandle(43)"
              class="price-input"
            />
            <i style="margin: 0 3px"> — </i>
            <el-input
              v-model.number="divideZoneItem.maxPercent"
              :readonly="!authorityHandle(43)"
              class="price-input"
            />

            <i
              v-if="authorityHandle(43)"
              v-show="index != 0"
              class="el-icon-remove"
              @click="removeDivideZoneItem(divideZoneItem.id, index)"
            />
            <i
              v-if="authorityHandle(43)"
              v-show="index === divideZone.divideZoneArray.length - 1"
              class="el-icon-circle-plus"
              @click="addDivideZoneItem(index)"
            />
          </li>
        </ul>
      </div>
    </k-dialog>

    <!-- 设置类别 弹窗 -->
    <k-dialog
      :show-hide.sync="categoryShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="类别配置"
      :show-foot="false"
      :two-btn="authorityHandle(43)"
      @click="categoryConfirm"
    >
      <div class="dialog-warningSetting new">
        <ul ref="dragSelect">
          <li
            v-for="(item, index) in categoryConfiguration"
            :key="index"
            style="margin-bottom: 30px"
          >
            <div class="dtitle">
              <span class="warning-title">类别名称 </span>
              <el-input
                v-model="item.name"
                class="price-input"
                placeholder="类别名称"
              />
              <el-input
                v-model.number="item.levelSort"
                class="price-input"
                placeholder="排名"
                style="margin-left: 20px"
              />
              <i
                v-if="authorityHandle(43)"
                class="el-icon-remove"
                @click="cancelCategory(item, index)"
                v-show="categoryConfiguration.length > 1"
              />
            </div>
            <div class="ssecond">
              <div
                class="item"
                v-for="(ele, idx) in item.settingDetail"
                :key="idx"
              >
                <span class="warning-title"
                  ><span
                    :style="{ background: ele.background_color }"
                    style="padding: 3px"
                    >{{
                      ele.level == "1" ? "金" : ele.level == "2" ? "红" : "蓝"
                    }}</span
                  >
                  箱价*</span
                >
                <el-input
                  v-model="ele.minMultiple"
                  onkeyup="value=value.replace(/[^0-9.]/g,'')"
                  :readonly="!authorityHandle(43)"
                  class="price-input short"
                />
                --
                <el-input
                  v-model="ele.maxMultiple"
                  onkeyup="value=value.replace(/[^0-9.]/g,'')"
                  :readonly="!authorityHandle(43)"
                  class="price-input short"
                />
                倍
              </div>
            </div>
          </li>
          <k-button class="top-btn" value="新增" @click.native="addCategory" />
        </ul>
      </div>
    </k-dialog>

    <!-- 一键打折 弹窗 -->
    <k-dialog
      :show-hide.sync="quickDiscountShow"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="一键打折"
      :show-foot="false"
      :two-btn="authorityHandle(43)"
      @click="saveDisCount"
    >
      <div style="padding: 50px">
        <el-form label-width="auto" :model="boxDiscount">
          <el-form-item label="箱子折扣：">
            <div style="display: flex">
              <el-input
                v-model="boxDiscount.discountValue"
                class="red_money"
                onkeyup="value=value.replace(/[^0-9.]/g,'')"
                placeholder="请输入数值"
              />%
            </div>
          </el-form-item>
          <el-form-item label="折扣时间：">
            <el-date-picker
              v-model="discountTime"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="datetimerange"
            />
          </el-form-item>
        </el-form>
      </div>
    </k-dialog>

    <!-- 晶粹配置 弹窗 -->
    <k-dialog
      :show-hide.sync="bulletSetting"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="晶粹配置"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(43)"
      @click="saveBulletSetting"
    >
      <div class="set_box">
        <div
          v-for="(item, index) in bulletSettingItemList"
          :key="item.id"
          class="Recharge_Data"
        >
          <div class="Recharge_Data_box">
            <span>晶粹数量:</span>
            <el-input
              v-model.trim="item.minAmmo"
              :readonly="!authorityHandle(43)"
            />
            <i style="margin: 0 2px"> — </i>
            <el-input
              v-model.trim="item.maxAmmo"
              :readonly="!authorityHandle(43)"
              style="margin-right: 20px"
            />
            <span>掉落概率:</span>
            <el-input
              v-model.trim="item.probability"
              :readonly="!authorityHandle(43)"
            />
            %
          </div>
          <div class="operation">
            <i
              v-if="authorityHandle(43)"
              v-show="index != 0"
              class="el-icon-remove"
              @click="deleteItem(item.id, index)"
            />
            <i
              v-if="authorityHandle(43)"
              v-show="index == bulletSettingItemList.length - 1"
              class="el-icon-circle-plus"
              @click="newlyAdded()"
            />
          </div>
        </div>
        <span>预期晶粹掉落数量：{{ getExpectedBulletNums() }}</span>
      </div>
    </k-dialog>

    <!-- 活动福利配置 弹窗 -->
    <k-dialog
      :show-hide.sync="welfareSetting"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="活动福利配置"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(43)"
      @click="saveWelfareData"
    >
      <div class="welfare_box">
        <el-form label-width="120px">
          <el-form-item label="所属活动：">
            <el-select
              v-model="welfareData.activityId"
              style="width: 100%"
              placeholder="请选择"
              :disabled="!authorityHandle(43)"
            >
              <el-option
                v-for="item in boxsResultList"
                :key="item.lineId"
                :label="item.lineName"
                :value="item.lineId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="福利掉落概率：">
            <div style="display: flex">
              <el-input
                v-model="welfareProbability"
                onkeyup="value=value.replace(/[^0-9.]/g,'')"
                :readonly="!authorityHandle(43)"
                placeholder="请输入"
              />
              %
            </div>
          </el-form-item>
          <div class="welfare_list">
            <div
              v-for="(item, index) in boxCardSettings"
              :key="index"
              class="welfare_item"
            >
              <span>添加福利</span>
              <el-select
                v-model="item.goodsId"
                style="width: 100%"
                placeholder="请选择"
                filterable
                @change="change($event, item)"
              >
                <el-option
                  v-for="value in resultList"
                  :key="value.lineId"
                  :label="value.lineName"
                  :value="value.lineId"
                />
              </el-select>

              <span>福利价值</span>
              <el-input
                v-model="item.customPrice"
                onkeyup="value=value.replace(/[^0-9.]/g,'')"
                readonly
                placeholder="请输入"
              />

              <span>掉落概率</span>
              <el-input
                v-model="item.probability"
                onkeyup="value=value.replace(/[^0-9.]/g,'')"
                :readonly="!authorityHandle(43)"
                placeholder="请输入"
              />
              <p>%</p>
              <i
                v-show="index == 0"
                class="el-icon-error"
                style="font-size: 16px; cursor: pointer; opacity: 0"
              />
              <i
                v-show="index != 0"
                class="el-icon-error"
                style="font-size: 16px; cursor: pointer"
                @click="curItem(index)"
              />
            </div>
            <div style="text-align: center">
              <i
                class="el-icon-circle-plus"
                style="font-size: 22px; color: #3b425d; cursor: pointer"
                @click="addItem"
              />
            </div>

            <p>预期掉落福利价值：{{ expected_value }}</p>
          </div>
        </el-form>
      </div>
    </k-dialog>
    <!-- 箱子限制 -->
    <k-dialog
      :show-hide.sync="addBoxShowHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="箱子限制设置/天"
      class="addBox-dialog"
      :two-btn="authorityHandle(43)"
      @click="saveItemDataClick"
    >
      <el-form :model="addItemInfo" label-width="auto" class="form-modify">
        <el-form-item label="限制开关：">
          <el-switch
            v-model="addItemInfo.astrictStatus"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
        <el-form-item label="限制个数：">
          <el-input
            v-model="addItemInfo.openNum"
            onkeyup="value=value.replace(/[^0-9.]/g,'')"
            style="width: 99%"
            show-word-limit
            placeholder="输入限制数量"
          >
            <template slot="append">个</template>
          </el-input>
        </el-form-item>
      </el-form>
    </k-dialog>
  </div>
</template>

<script>
import {
  getOpenBoxWarningSetting,
  setOpenBoxWarningSetting,
  getListGeneralData,
  saveGeneralData,
  boxUpdateBoxastrictStatus,
  deleteGeneralData,
  getBoxStageList,
  setBoxStageList,
} from "@/api/rules/listdata";
import {
  getAmmoBoxList,
  setAmmoBoxList,
  getBoxLeveSetting,
  setBoxLeveSetting,
  checkBoxLeveSetting,
} from "@/api/bullet/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { addCardSetting, getCardSetting, listSelect } from "@/api/activity.js";
import { getGoodsPlatformList } from "@/api/rules/listdata";
import { setListQuery, removeListQuery, getListQuery } from "@/utils/auth"; // get token from cookie
import Sortable from "sortablejs";
import {deepClone} from '@/utils'
export default {
  components: { Pagination },
  dicts: ["BOX_UPDOWN_STATUS"],
  data() {
    const validateLogo = (rule, value, callback) => {
      if (!this.addBoxInfo.imgUrl) {
        callback(new Error('请上传'))
      } else {
        callback()
      }
    }
    return {
      categoryShow: false,
      smartWarningModel: {
        percentTime: undefined,
        percentValue: undefined,
        numTime: undefined,
        numValue: undefined,
      },
      currentBoxId: undefined,
      bulletSettingItemList: [
        {
          id: undefined,
          boxId: undefined,
          minAmmo: undefined,
          maxAmmo: undefined,
          probability: undefined,
        },
      ],
      divideZone: {
        divideZoneArray: [
          {
            id: undefined,
            boxId: -1,
            minPercent: "",
            maxPercent: "",
            openSort: 0,
          },
        ],
      },
      multipleSelection: [],
      addBoxInfo: {
        id: "", // 保存箱子配置时必传",
        imgUrl: "", // 箱子图标",
        goodsImgUrl: "", // 饰品展示缩略图",
        boxName: "", // 箱子名称",
        openAnimationUrl: "",
        stopUrl: "",
        levelId: "", // 选择类别
      },
      boxList: [],
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: "",
          start: "",
        },
        boxStatus: undefined, // 上架1  下架2,
        startTime: undefined, // 饰品外观',
        endTime: undefined, // 饰品类别',
        key: "", // 箱子名称或关键词 箱子配置界面所用'
      },
      adminuserinfo: {
        username: "",
        password: "",
        nickname: "",
      },
      adminrules: {
        nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
      },
      rules:{
        boxName: [
            { required: true, message: '请输入', trigger: 'blur' },
          ],
          levelId:[
            { required: true, message: '请选择', trigger: ['blur','change'] },
          ],
          imgUrl:[
            { required: true, validator: validateLogo, trigger: 'change' },
          ]
      },
      timeValue: "",
      conditions: {
        keyword: null,
      },
      addBox: {
        showHide: false,
      },
      addBoxUpdate: {
        showHide: false,
      },
      quickDiscountShow: false,
      boxDiscount: {
        discountValue: 0,
        startTime: undefined,
        endTime: undefined,
      },
      discountTime: "",
      bulletSetting: false,
      smartDivideZoneDialog: false,
      smartWarningDialog: false,
      dialogStatus: "create",
      textMap: {
        update: "修改箱子",
        create: "添加箱子",
      },

      /* 活动福利配置*/
      welfareSetting: false, // 弹框
      resultList: [], // 全部饰品

      boxsResultList: [],
      welfareProbability: undefined,
      welfareData: {
        boxCardSettings: [],
        boxId: undefined,
        activityId: "",
      },
      boxCardSettings: [
        {
          probability: undefined,
          goodsId: undefined,
          customPrice: undefined,
        },
      ],
      expected_value: 0,
      // 添加限制
      addItemInfo: {
        id: "",
        openNum: 0,
        astrictStatus: 2,
      },
      addBoxShowHide: false,
      selectCategoryOptions: [],
      categoryConfiguration: [
        {
          name: "", // 类别名称
          levelSort: "", // 排名
          settingDetail: [
            {
              level: "1",
              minMultiple: "",
              maxMultiple: "",
              background_color: "#ffc400",
            },
            {
              level: "2",
              minMultiple: "",
              maxMultiple: "",
              background_color: "#f51107",
            },
            {
              level: "3",
              minMultiple: "",
              maxMultiple: "",
              background_color: "#0c7be9",
            },
          ],
        },
      ],
      deleteCategoryList: [],
    };
  },
  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null;
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null;
    },
    'addBoxInfo.imgUrl':{
      immediate:false,
      handler(newVal, oldVal) {
        if (newVal) {
          this.$refs.addBoxInfo.clearValidate('imgUrl')
        }
      }
    },
  },
  mounted() {
  },
  created() {
    this.loadData();
    this.getSmartDivideZone();
  },

  methods: {
    // 类别配置弹窗
    async categoryShowHandler() {
      this.categoryShow = true;
      const res = await getBoxLeveSetting();
      if (res.status === 200 && res.data.length != 0) {
        res.data.map((v) => {
          v.settingDetail = JSON.parse(v.settingDetail);
        });
      }
      this.categoryConfiguration = res.data;
      // 拖动排序
      // this.setSort();
    },
    // 类别配置确认
    async categoryConfirm() {
      let type = this.categoryConfiguration.every(
        (item) => item.name && item.levelSort
      );
      let info = this.categoryConfiguration
        .map((element) => {
          return element.settingDetail.every(
            (ele) => ele.minMultiple && ele.maxMultiple
          );
        })
        .every((k) => k);
      if (type && info) {
        let arr = this.categoryConfiguration;
        let data = {
          updateList: arr,
          deleteList: this.deleteCategoryList,
        };
        const res = await setBoxLeveSetting(data);
        if (res.status == 200) this.deleteCategoryList = [];
        this.$message.success("保存成功");
        this.categoryShow = false;
      } else {
        this.$message.error("请输入完整");
      }
    },
    // 动态排序
    setSort() {
      const el = this.$refs.dragSelect;
      const arr = deepClone(this.categoryConfiguration)
      // 设置配置
      const ops = {
        animation: 1000,
        // 拖动结束
        onEnd: (evt)=> {
           const oldItem = arr[evt.oldIndex];
           arr.splice(evt.oldIndex, 1);
           arr.splice(evt.newIndex, 0, oldItem);
           this.categoryConfiguration= []
           this.$nextTick(()=>{
            this.categoryConfiguration = arr
           })
        },
      };
      // 初始化
      Sortable.create(el, ops);
      
    },
    // 类别配置新增
    addCategory() {
      let obj = {
        name: "", // 类别名称
        levelSort: "",
        settingDetail: [
          {
            level: "1",
            minMultiple: "",
            maxMultiple: "",
            background_color: "#ffc400",
          },
          {
            level: "2",
            minMultiple: "",
            maxMultiple: "",
            background_color: "#f51107",
          },
          {
            level: "3",
            minMultiple: "",
            maxMultiple: "",
            background_color: "#0c7be9",
          },
        ],
      };

      this.categoryConfiguration.push(obj);
    },
    // 类别配置删除
    async cancelCategory(item, index) {
      console.log(item);
      const res = await checkBoxLeveSetting({ id: item.id || "" });
      if (res.data.success){
        this.categoryConfiguration.splice(index, 1);
      }else{
        this.$message.error(res.data.msg);
      }
    },
    filterTag(value, row) {
      return row.boxStatus === value;
    },
    /* 活动福利配置*/
    welfareSettingDialog(row) {
      this.getGoodsPlatformList(row);
    },

    // 请求饰品
    getGoodsPlatformList(row) {
      getGoodsPlatformList({ key: "", alreadyIds: "[-1]" }).then((res) => {
        this.resultList = [];
        Object.assign(this.resultList, res.data);
        listSelect().then((res) => {
          this.boxsResultList = res.data;
          this.welfareData.boxId = row.id;

          getCardSetting({ boxId: row.id }).then((res) => {
            const data = res.data.data;
            if (data.value) {
              this.welfareProbability = res.data.data.settingList.find(
                (item) => item.goodsId == -1
              ).probability;
              this.boxCardSettings = res.data.data.settingList.filter(
                (item) => item.goodsId !== -1
              );
              this.expected_value = res.data.data.value;
              this.welfareData.activityId = this.boxCardSettings[0].activityId;
              this.welfareData.boxId = row.id;
              this.welfareSetting = true;
            } else {
              this.welfareData.activityId = undefined;
              this.welfareData = this.$options.data.call(this).welfareData;
              this.boxCardSettings =
                this.$options.data.call(this).boxCardSettings;
              this.welfareProbability =
                this.$options.data.call(this).welfareProbability;
              this.expected_value =
                this.$options.data.call(this).expected_value;
              this.welfareData.boxId = row.id;
              this.welfareSetting = true;
            }
          });
        });
      });
    },

    change(e, item) {
      const data = this.resultList.find((value) => value.lineId == e);
      item.customPrice = data.price;
    },

    // 单个删除
    curItem(index) {
      this.boxCardSettings.splice(index, 1);
    },

    addItem() {
      this.boxCardSettings.push({
        probability: undefined,
        goodsId: undefined,
        customPrice: undefined,
      });
    },

    // 保存活动
    saveWelfareData() {
      if (!this.welfareData.activityId) {
        this.$message.error("所属活动必填");
        return;
      }

      if (!this.welfareProbability) {
        this.$message.error("福利掉落概率必填");
        return;
      }
      const status = this.boxCardSettings.every(
        (item) => item.probability && item.goodsId && item.customPrice
      );
      if (!status) {
        this.$message.error("福利各项必填");
        return;
      }

      const item = {
        probability: this.welfareProbability,
        goodsId: -1,
        customPrice: 0,
      };
      const list = this.boxCardSettings.concat();
      list.unshift(item);
      this.welfareData.boxCardSettings = list;
      addCardSetting(this.welfareData).then((res) => {
        if (res.data.success) {
          this.$message.success(res.data.msg);
          this.welfareSetting = false;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },

    /**/

    quickDiscount() {
      this.quickDiscountShow = true;
    },
    datetimerange(timeValue) {
      this.boxDiscount.startTime = this.discountTime ? timeValue[0] : null;
      this.boxDiscount.endTime = this.discountTime ? timeValue[1] : null;
    },
    // 设置新增
    newlyAdded() {
      this.bulletSettingItemList.push({
        id: undefined,
        boxId: undefined,
        minAmmo: undefined,
        maxAmmo: undefined,
        probability: undefined,
      });
    },
    // 设置删除
    deleteItem(value, indexItem) {
      if (!value) {
        this.bulletSettingItemList.splice(indexItem, 1);
        return;
      }
      var index = this.bulletSettingItemList.findIndex(function (item) {
        return item.id === value;
      });
      if (index !== -1) {
        this.bulletSettingItemList.splice(index, 1);
      }
    },

    removeDivideZoneItem(value) {
      const index = this.divideZone.divideZoneArray.findIndex(function (item) {
        return item.id === value;
      });
      if (index !== -1) {
        this.divideZone.divideZoneArray.splice(index, 1);
      }
      this.divideZone.divideZoneArray.map((item, index) => {
        item.openSort = index;
      });
    },
    addDivideZoneItem(index) {
      this.divideZone.divideZoneArray.push({
        id: undefined,
        boxId: -1,
        minPercent: "",
        maxPercent: "",
        openSort: index + 1,
      });
    },
    // 保存折扣
    saveDisCount() {},
    getSmartDivideZone() {
      getBoxStageList({ id: -1 }).then((res) => {
        this.divideZone.divideZoneArray = res.data;
      });
    },
    saveSmartDivideZone() {
      this.divideZone.divideZoneArray.map((item) => {
        item.boxId = -1;
      });
      setListQuery(this.listQuery);
      setBoxStageList(this.divideZone.divideZoneArray).then((res) => {
        if (res.data.success) {
          this.$message.success("保存成功");
          this.smartDivideZoneDialog = false;
          this.loadData();
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    // 智能分区
    smartDivideZone() {
      this.smartDivideZoneDialog = true;
    },
    // 智能预警
    smartWarning() {
      getOpenBoxWarningSetting().then((res) => {
        this.smartWarningModel = res.data;
        this.smartWarningDialog = true;
      });
    },
    saveSmartWarning() {
      setOpenBoxWarningSetting(this.smartWarningModel).then((res) => {
        this.$message.success("保存成功");
        this.smartWarningDialog = false;
      });
    },
    loadData() {
      if (getListQuery()) {
        this.listQuery = getListQuery();
        if (getListQuery().startTime && getListQuery().endTime)
          this.timeValue = [getListQuery().startTime, getListQuery().endTime];
      }
      getListGeneralData(this.listQuery).then((res) => {
        const data = res.data;
        this.boxList = data.rows;
        this.totalRows = data.totalRows;
        removeListQuery();
      });
    },
    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
      this.listQuery.sort = column.prop;
      if (column.order === "ascending") {
        this.listQuery.direction = "asc";
      } else if (column.order === "descending") {
        this.listQuery.direction = "desc";
      }
      this.loadData();
    },
    // 搜索查询事件
    handleFilter() {
      this.loadData();
    },
    // 删除箱子
    deleteBox() {
      const _vue = this;
      if (_vue.multipleSelection.length < 1) {
        this.$message.error("请至少选择一条数据进行删除！");
        return;
      }
      const selections = _vue.multipleSelection;
      console.log(selections);
      this.$confirm("确定删除选中的箱子么?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [];
          for (var i = 0; i < selections.length; i++) {
            ids.push(selections[i].id);
          }
          deleteGeneralData({ ids: ids }).then((res) => {
            if (res.data.success) {
              this.$message.success("删除成功");
              this.loadData();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    async addBoxDialog() {
      this.$resetForm(this.addBoxInfo);
      this.addBox.showHide = true;
      const res = await getBoxLeveSetting();
      this.selectCategoryOptions = res.data || [];
      this.$refs.addBoxInfo.clearValidate();
    },
    getExpectedBulletNums() {
      const expectBulletNums = this.bulletSettingItemList
        .map((item) => {
          return (
            ((Number(item.minAmmo) + Number(item.maxAmmo)) / 2) *
            item.probability
          );
        })
        .reduce(function (a, b) {
          return Number(a) + Number(b);
        });
      this.$log(expectBulletNums,'aaaaa');
      this.$log(this.bulletSettingItemList,'bbb');
      return expectBulletNums / 100;
    },
    saveBulletSetting() {
      const probSum = this.bulletSettingItemList
        .map((item) => {
          return item.probability;
        })
        .reduce(function (a, b) {
          return Number(a) + Number(b);
        });
      this.$log(probSum,'vvvvv');
      if (100 - Number(probSum).toFixed(2) !== 0) {
        this.$message.error(
          "掉落概率和要等于100,还需要 " + (100 - probSum).toFixed(2)
        );
        return;
      }
      this.bulletSettingItemList.map((item) => {
        item.boxId = this.currentBoxId;
      });
      setAmmoBoxList(this.bulletSettingItemList).then((res) => {
        this.$message.success("保存成功");
        this.bulletSetting = false;
      });
    },
    bulletSettingDialog(row) {
      this.bulletSetting = true;
      this.currentBoxId = row.id;
      getAmmoBoxList({ boxId: row.id }).then((res) => {
        this.bulletSettingItemList = res.data;
      });
    },
    async addBoxUpdateDialog(row) {
      console.log(row);
      this.addBoxUpdate.showHide = true;
      this.addBoxInfo.id = row.id;
      this.addBoxInfo.boxName = row.boxName;
      this.addBoxInfo.imgUrl = row.imgUrl;
      this.addBoxInfo.goodsImgUrl = row.goodsImgUrl;
      this.addBoxInfo.openAnimationUrl = row.openAnimationUrl;
      this.addBoxInfo.stopUrl = row.stopUrl;
      this.addBoxInfo.levelId = row.levelId
      const res = await getBoxLeveSetting();
      this.selectCategoryOptions = res.data || [];
    },
    successUpload(data, flag) {
      if (flag === 0) {
        this.addBoxInfo.imgUrl = data;
      } else if (flag === 1) {
        this.addBoxInfo.goodsImgUrl = data;
      } else if (flag === 2) {
        this.addBoxInfo.openAnimationUrl = data;
      } else if (flag === 3) {
        this.addBoxInfo.stopUrl = data;
      }
    },
    // 添加箱子
    saveBoxData() {
      this.$refs.addBoxInfo.validate((valid) => {
          if (!valid) return this.$message.error("请填写完整!");
          setListQuery(this.listQuery);
          saveGeneralData(this.addBoxInfo).then((res) => {
            if (res.data.success) {
              this.$message.success("保存成功");
              this.handleFilter();
            } else {
              this.$message.error(res.data.msg);
            }
            this.$resetForm(this.addBoxInfo);
            this.addBox.showHide = false;
            this.addBoxUpdate.showHide = false;
          });
        });
        return
      
    },
    handleCloseDialog() {
      this.$resetForm(this.addBoxInfo);
      this.addBox.showHide = false;
    },
    // 跳转配置饰品
    configBabyLib(boxid, permissionid) {
      setListQuery(this.listQuery);
      this.$router.push({
        path: "/rootplayrules/config-babylibnew",
        query: { id: boxid, permissionid },
      });
    },
    // 添加箱子限制
    addItemDialog(row) {
      this.addBoxShowHide = true;
      this.addItemInfo = { ...row };
    },
    // 保存箱子数
    saveItemDataClick() {
      boxUpdateBoxastrictStatus(this.addItemInfo).then((res) => {
        if (res.data.success) {
          this.$message.success("保存成功");
          this.handleFilter();
        } else {
          this.$message.error(res.data.msg);
        }
        this.addBoxShowHide = false;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
$menuText: #14162e; // 侧边栏字体颜色
$hoverColor: #1d143c; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.warning_div {
  .second {
    line-height: 40px;
    margin-left: 10px;
  }
}

.dialog-warningSetting {
  &.new {
    position: relative;
    ul {
      li {
        display: flex;
        flex-direction: column;
        .ssecond {
          display: flex;
          max-width: 960px;
          flex-wrap: wrap;
        }
        .item {
          margin-right: 20px;
          margin-bottom: 10px;
        }
      }
    }
    .el-icon-remove {
    }
  }
  ::v-deep.el-input {
    width: 110px;
  }

  .dtitle {
    margin-bottom: 20px;
    width: 960px;
  }
  .price-input {
    width: 150px;
    &.short {
      width: 60px;
    }
  }

  .el-icon {
    &-circle-plus,
    &-remove {
      font-size: 22px;
      color: #3b425d;
      margin-left: 10px;
    }
  }
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;

  li {
    // margin: 0 0 30px 0px;
    display: flex;
    flex-direction: row;
    align-items: center;

    .warning-title {
      font-size: 16px;
      color: #14162e;
      margin-right: 30px;
    }

    i {
      color: #d1d5dd;
    }
  }
}

.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }

  .kInput {
    position: absolute;
    right: 20px;
  }

  .filter-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162e;
  }

  .user-item {
    margin-left: 10px;
    margin-right: 20px;
  }

  .user-status,
  .account-status {
    margin-right: 20px;
  }
}

.top-btn {
  margin: 30px 0px 30px 0px;
  font-size: 14px;
  color: #ffffff;

  &:nth-of-type(2) {
    margin-left: 20px;
  }

  &:nth-of-type(3) {
    margin-left: 20px;
  }

  &:nth-of-type(4) {
    margin-left: 20px;
  }
}

::v-deep .el-input__inner:focus {
  border-color: $mainColor;
}

.el-form-item__label-wrap .el-form-item__label {
  float: none;
}

.dialog-openboxsetting {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 80px 80px;
}

.form-modify {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin: 10px 80px;

  .modify-right {
    margin-left: 80px;
  }

  ::v-deep .el-input__inner {
    // border-color: $mainColor;
    width: 200px;
  }
}

.addBox-dialog {
  ::v-deep .el-dialog__body {
    padding: 10px 80px;
  }

  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 40px;
  }
}

.upload-btn {
  font-size: 14px;
  color: #ffffff;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.welfare_box {
  width: 740px;
  margin: 0 40px;
  box-sizing: border-box;

  .el-input {
    width: 300px;
    margin-right: 10px;
  }

  .el-select {
    width: 300px !important;
  }

  .welfare_list {
    width: 660px;
    // border: 1px solid red;
    transform: translateX(30px);

    .welfare_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;

      span {
        font-size: 14px;
        font-weight: bold;
      }

      .el-input {
        width: 120px;
        margin: 0;
      }

      .el-select {
        width: 120px !important;
      }

      p {
        font-size: 14px;
        transform: translateX(-10px);
      }
    }
  }
}

.set_box {
  width: 700px;
  margin: 0 80px;
  box-sizing: border-box;

  .Recharge_Data {
    width: 100%;
    height: 40px;
    margin-top: 10px;
    margin-bottom: 30px;
    display: flex;
    align-items: center;

    .Recharge_Data_box {
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-input {
        width: 150px;
        height: 35px;

        input {
          width: 150px;
          height: 35px;
        }
      }

      span {
        font-size: 14px;
        width: 100px;
      }
    }

    .operation {
      width: 12%;
      display: flex;
      justify-content: space-between;

      .el-icon {
        &-circle-plus,
        &-remove {
          font-size: 22px;
          color: #3b425d;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
